
$(function(){
	$init();
});

var obj = {}
	obj.uin=''; //QQ号
	obj.categoryId='0'; //自定义分类ID
	obj.orderType='2'; //商品排序方式
	obj.modTitle=''; //模块标题
	obj.modType=''; //模块风格
	obj.modWidth=''; //模块宽度
	obj.modPicSize=''; //模块图片尺寸
	obj.pageIndex="1";
	obj.pageTotal='';
	obj.isFirst=true;

// 初始化
function $init(){
	//根据QQ号码拉取店铺自定义分类
	$('#getCatLink').click(function(){
		if($('#iptUin').val() != ''){
			$('#getCatLink').addClass('hide');
			$('#iptCat').removeClass('hide');
			obj.uin = $('#iptUin').val();
			$getShopCategoryList();
			return false;
		}
		else {
			alert('请输入QQ号！');
		}
	});

	//拉取商品列表
	$('#iptCat').change(function(){
		obj.categoryId = $('#iptCat option:selected').attr('categoryId');
		
		$getItemList();
	});

	//获取商品排序方式
	$('#iptSort').change(function(){
		obj.orderType = $('#iptSort option:selected').attr('orderType');

		$getItemList();
	});

	//页面刷新之后禁用排序功能
	if($('.item-add .item-list ul').html() == ''){
		$('#iptSort').attr('disabled','disabled');
	}

	//添加商品
	$('#itemListView .item-price a').live('click',function(){
		
		//var $index = $(this).parent().parent().index();
		//console.log($index);
		//var $itemUintCode = $('#itemListView li').clone()[$index];
		var $itemUintCode = $(this).parent().parent().clone();
		$itemUintCode.find('.item-price a').text('删除').click(function(){
			$(this).parent().parent().remove();
		}).parent().parent().find('img').attr('src')[0].replace('')
		
		console.log($($itemUintCode).html());
		$('#sellerCode .demo').remove();
		$('#sellerCode .seller-code .sbd ul').append($itemUintCode);
		$(this).replaceWith('<span style="color:gray;">已添加</span>');

	});


	//获取模块标题
	obj.modTitle = $('#iptTitle').val();
	
	$('#iptTitle').change(function(){
		if($('#iptTitle').val() != ''){
			obj.modTitle = $('#iptTitle').val();
			$preview();
		}
		else {
			alert('请输入模块标题！');
		}
	});
	
	//获取模块风格
	obj.modType = $('#iptTheme [type="radio"]:checked').val();
	
	$('#iptTheme').change(function(){
		obj.modType = $('#iptTheme [type="radio"]:checked').val();
		$preview();
	});
	
	//获取模块宽度
	obj.modWidth = $('#iptModWidth option:selected').attr('modWidth');
	
	$('#iptModWidth').change(function(){
		obj.modWidth = $('#iptModWidth option:selected').attr('modWidth');
		$preview();
	});
	
	//获取图片尺寸
	obj.modPicSize = $('#iptPicSize option:selected').attr('picSize');
	
	$('#iptPicSize').change(function(){

		obj.modPicSize = $('#iptPicSize option:selected').attr('picSize');
		$preview();
	});

	//
	$('#copyCode textarea').html($('#sellerCode').html());

	
	//翻页
	//optional set
	pageNav.pre='&laquo; 上一页';
	pageNav.next='下一页 &raquo;';

	// Custom your function. Load the page content with ajax or change the window.location;
	//@param  p:current page number.  
	//@param  pn: page sum.
	pageNav.fn = function(p,pn){
		obj.pageIndex = p;
		console.log('obj.isFirst1:',obj.isFirst);
		$getItemList();
		//$("#paper").removeClass('hide').text("Page:"+p+" of "+pn + " pages.");
		console.log('obj.pageIndex3:',obj.pageIndex,'   obj.pageTotal3:',obj.pageTotal);
	}

	//goto the page 1 of total.
	console.log('obj.pageIndex:',obj.pageIndex,'   obj.pageTotal:',obj.pageTotal);

	if(obj.isFirst)return;
	else{
		pageNav.go(obj.pageIndex,obj.pageTotal);
	}


}
//预览效果
function $preview(){
	var $sellerCode ='<!-- seller code begin --><div class="seller-code sc-s' + obj.modType + '" style="width:' + obj.modWidth + 'px"><div class="inner"><div class="shd"><h4>' + obj.modTitle + '</h4></div><div class="sbd"><ul><li><a href="http://auction1.paipai.com/98FCAF150000000000183B5007EC35D0"><img src="img/300x300.png"></a><p class="item-title">新 2011新款女装 HodooAge 大西瓜 韩版可爱女装短袖T恤 TS1139</p><p class="item-price">¥39.00</p></li><li><a href="http://auction1.paipai.com/98FCAF150000000000183B5007EC38EF"><img src="img/300x300.png"></a><p class="item-title">新 2011新款女装 HodooAge 乡间小路 韩版可爱女装短袖T恤 TS1146</p><p class="item-price">¥39.00</p></li><li><a href="http://auction1.paipai.com/98FCAF150000000000183B5007EC7780"><img src="img/300x300.png"></a><p class="item-title">新 2011新款女装 HodooAge 师徒全家福女装T恤 可配情侣装 TS1145</p><p class="item-price">¥39.00</p></li></ul></div></div></div><!-- seller code end -->'
	//$('#sellerCode').html($sellerCode);

	$('#sellerCode li').each(function(){
		var $src = $(this).find('img').attr('src');
		$src = $src.substring(0,$src.indexOf('.0.'))+'.0.'+$('#iptPicSize option:selected').attr('picSize')+'x'+$('#iptPicSize option:selected').attr('picSize')+'.jpg';
		console.log($src);
		$(this).find('img').attr('src',$src);
	});
	//return false;
};

//获取商品分类
function $getShopCategoryList(){
	$.ajax({
		url:'get-api.php?pureData=1&api=/shop/getShopCategoryList.xhtml&sellerUin=' + obj.uin,
		dataType:'json',
		cache:false,
		beforeSend:function(){
			$('#getCat .loading').html('<img src="img/loading.gif" />');
		},
		complete:function(){
			$('#getCat .loading').remove();
		},
		success:function(data) {
			if(data.errorCode == '0' && data.shopCategoryList != null){
				
				console.time('timer1');
                   
                var $opt = document.createDocumentFragment();

                $.each(data.shopCategoryList.shopCategory,function(i,el){
					if(el.hasLeaf == 'true' && el.htmlFragment == undefined){
						el.htmlFragment = $('<optgroup label="'+ el.desc + '" categoryId="' + el.categoryId + '"></optgroup>')[0];
                        $opt.appendChild(el.htmlFragment);
                        //console.log($('<optgroup label="'+ el.desc +'"></optgroup>'));
                    }
                    else{
						if(el.level == '1'){
							el.htmlFragment = $('<option categoryId="' + el.categoryId + '">'+ el.desc +'</option>')[0];
					        $opt.appendChild(el.htmlFragment);
                        }
                        else{
							el.htmlFragment = $('<option categoryId="' + el.categoryId + '">'+ el.desc +'</option>')[0];
							$.each(data.shopCategoryList.shopCategory,function(j,el2){
                                       
							    if(el.parentId === el2.categoryId){
									if(el2.htmlFragment){
										$(el2.htmlFragment).append(el.htmlFragment);
									}
								    else{
										el2.htmlFragment = $('<optgroup label="'+ el2.desc +'"></optgroup>')[0];
									    $(el2.htmlFragment).append(el.htmlFragment);
								    }
								}
                            });
						}
                    }
                });

				$('#iptCat').empty().html('<!--<option>请选择商品分类</option>--><option categoryId="0">未分类商品</option>').append($opt);
                console.timeEnd('timer1');

				//拉取分类成功后立即获取商品列表
				$getItemList();
				
				$('#iptSort').removeAttr('disabled');
			}
			else if(data.errorCode == '0' && data.shopCategoryList === null){
				$('#iptCat').addClass('hide');
				$('#getCat .noCat').empty().html('此QQ号码暂时没有自定义分类，请刷新页面，更换QQ号码再试！').css('color','red');;
				//alert('没有自定义分类！');
			}
			else {
				console.log('获取分类失败，请确认QQ号码是否正确！');
			}
		},
		error:function() {
			console.log('error');
		}
	});
}

// 拉取商品列表
function $getItemList(){
	$.ajax({
		url:'get-api.php?pureData=1&api=/item/buyerSearchItemList.xhtml&itemState=1&sellerUin=' + obj.uin + '&itemState=1&pageSize=7&pageIndex=' + obj.pageIndex + '&orderType=' + obj.orderType + '&categoryId=' + obj.categoryId,
		dataType:'json',
		cache:false,
		beforeSend:function(){
			$('#getItem .loading').html('<img src="img/loading.gif" /> 加载中...');
		},
		complete:function(){
			$('#getItem .loading').remove();
		},
		success:function(data) {
			if(data.errorCode == "0"){

				var $item = document.createDocumentFragment();
				$.each(data.itemList.item,function(){
					$itemList = this;
					//console.log($itemList);
					
					//转换商品价格
					var $itemPrice = $itemList.itemPrice;
					$itemPrice = $itemPrice.substring(0,$itemPrice.length-2) + '.' + $itemPrice.substring($itemPrice.length-2,$itemPrice.length);

					//输出商品单元
					$item.htmlCode = $('<li><a href="http://auction1.paipai.com/' + $itemList.itemCode 
									+ '">' + '<img src="' + $itemList.picLink.split('.jpg')[0] 
									+ '.120x120.jpg" />' +'</a><p class="item-title">' +  $itemList.itemName + '</p><p class="item-price">&yen;' + $itemPrice + '&nbsp;&nbsp;&nbsp;&nbsp;<a href="#nolink">添加</a></p></li>')[0];
					$item.appendChild($item.htmlCode);
					//$('#paper').removeClass('hide');
					


				});
				$('#itemListView ul').empty().append($item);
				
				obj.pageTotal = data.pageTotal;
				console.log('obj.isFirst2',obj.isFirst)
				if(obj.isFirst){
					pageNav.go(obj.pageIndex,obj.pageTotal);
					obj.isFirst = false;
					console.log('obj.pageIndex2:',obj.pageIndex,'   obj.pageTotal2:',obj.pageTotal);
				}

	
			}
			else {
				alert("获取商品列表失败，请稍后刷新页面再试！");
			}
		},
		error:function() {
			//alert("error");
			console.log('error');
		}
	});
}

